<template>
  <q-btn class="btn margin-r-10"
         :outline="!isFlat"
         :flat="isFlat"
         color="primary"
         :label="label"
         :disable="disable || isDisable"
         @click="exportExcel"/>
</template>

<script>
import moment from 'moment'
import { mapGetters } from 'vuex'

export default {
  name: 'export-btn',
  props: {
    disable: { // 禁用条件
      type: Boolean,
      default: false
    },
    exportFun: { // 导出方法
      type: Function
    },
    exportParams: { // 导出报表参数
      type: Object
    },
    exportName: { // 导出文件名称
      type: String,
      default: '导出文件.xls'
    },
    label: { // 导出按钮名称
      type: String,
      default: '导出Excel'
    },
    isFlat: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  data () {
    return {
      isDisable: false,
      requestId: '' // 导出标识
    }
  },
  methods: {
    // 导出excel
    exportExcel () {
      this.isDisable = true
      this.$q.loading.show()
      // 表格表头
      const exportParams = {
        ...this.exportParams
      }
      this.$q.loading.show()
      const params = [{ name: moment().format() }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      exportParams['requestId'] = res.fileNameNew
      this.onSubscribe()
      this.exportFun(exportParams).then(res => {
        if (res.code + '' !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, this.exportName)
      this.closeUbscribeTopic()
      this.$utils.showMessage('icontubiao-53', '数据请求成功,请保存文件')
    },
    closeUbscribeTopic () {
      this.$q.loading.hide()
      this.isDisable = false
      this.client.unsubscribe(`${this.requestId}`)
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    }
  }
}
</script>

<style scoped>

</style>
